<template>
  <div id="main">
    <div class="login-container">
      <h1>登录</h1>
      <a-tabs
          v-model:active-key="activeKey"
          :tabBarStyle="{ textAlign: 'center', borderBottom: 'unset' }"
          @change="handleTabClick"
          class="centered-tabs"
          centered
      >
        <a-tab-pane key="0" tab="账号登录">
          <a-alert
              v-if="isLoginError"
              type="error"
              showIcon
              style="margin-bottom: 24px;"
              message="账号或密码错误，请重新输入"
          />
          <a-form
              :form="accountFormRef"
              name="account-login"
              @finish="handleAccountLogin"
              :scrollToFirstError="true"
          >
            <a-form-item
                name="username"
                :rules="[{ required: true, message: '请输入账号' }]"
            >
              <a-input v-model:value="accountUsername" placeholder="账号" />
            </a-form-item>
            <a-form-item
                name="password"
                :rules="[{ required: true, message: '请输入密码' }]"
            >
              <a-row>
                <a-col :span="24">
                  <a-input-password
                      v-model:value="accountPassword"
                      placeholder="密码"
                  />
                </a-col>
              </a-row>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" html-type="submit" block>登录</a-button>
            </a-form-item>
          </a-form>
        </a-tab-pane>
        <a-tab-pane key="1" tab="手机号登录">
          <a-form
              :form="phoneFormRef"
              name="phone-login"
              @finish="handlePhoneLogin"
              :scrollToFirstError="true"
          >
            <a-form-item
                name="phone"
                :rules="[{ required: true, message: '请输入手机号' }, { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }]"
            >
              <a-input v-model:value="phoneNumber" placeholder="手机号" />
            </a-form-item>
            <a-form-item
                name="code"
                :rules="[{ required: true, message: '请输入验证码' }]"
            >
              <a-row>
                <a-col :span="16">
                  <a-input v-model:value="verificationCode" placeholder="验证码" />
                </a-col>
                <a-col :span="8">
                  <a-button
                      @click="getCaptcha"
                      class="get-code-btn"
                      :disabled="smsSendBtn"
                  >{{ smsSendBtnText }}</a-button>
                </a-col>
              </a-row>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" html-type="submit" block>登录</a-button>
            </a-form-item>
          </a-form>
        </a-tab-pane>
      </a-tabs>
      <!-- 分割线 -->
      <div class="divider">
        <span>其他登录方式</span>
      </div>
      <!-- 新增第三方登录部分 -->
      <div class="third-party-login">
        <a-button @click="handleThirdPartyLogin('qq')" class="round-button">
          <img src="https://img.icons8.com/color/48/000000/qq.png" alt="QQ" />
        </a-button>
        <a-button @click="handleThirdPartyLogin('wechat')" class="round-button">
          <img src="https://img.icons8.com/color/48/000000/wechat.png" alt="微信" />
        </a-button>
        <a-button @click="handleThirdPartyLogin('weibo')" class="round-button">
          <img src="https://img.icons8.com/color/48/000000/weibo.png" alt="微博" />
        </a-button>
      </div>
    </div>
    <div class="copyright">
      &copy; 2025 Your Company. All rights reserved.
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted } from 'vue';
import type { FormInstance } from 'ant-design-vue';
import { message } from 'ant-design-vue';

// 登录错误状态
const isLoginError = ref<boolean>(false);
// 登录类型 0- 账号登录 1 手机登录
const activeKey = ref<string>('0');
// 表单引用
const accountFormRef = ref<FormInstance | null>(null);
const phoneFormRef = ref<FormInstance | null>(null);
// 账号登录表单数据
const accountUsername = ref<string>('');
const accountPassword = ref<string>('');
// 手机号登录表单数据
const phoneNumber = ref<string>('');
const verificationCode = ref<string>('');
// 验证码按钮状态
const smsSendBtn = ref<boolean>(false);
const smsSendBtnText = ref<string>('获取验证码');
// 倒计时定时器
let countdownTimer: number | null = null;

// 封装倒计时函数
const startCountdown = () => {
  let countdown = 60;
  smsSendBtn.value = true;
  smsSendBtnText.value = `${countdown}s 后重试`;
  countdownTimer = setInterval(() => {
    countdown--;
    if (countdown > 0) {
      smsSendBtnText.value = `${countdown}s 后重试`;
    } else {
      clearInterval(countdownTimer as number);
      smsSendBtn.value = false;
      smsSendBtnText.value = '获取验证码';
    }
  }, 1000);
};

onMounted(() => {
  console.log('页面挂载完成');
});

onUnmounted(() => {
  // 组件卸载时清除定时器
  if (countdownTimer) {
    clearInterval(countdownTimer);
  }
});

// 切换登录方式
const handleTabClick = (key: string): void => {
  activeKey.value = key;
  console.log(key);
  // 切换登录方式时重置错误状态
  isLoginError.value = false;
  // 重置表单数据
  if (key === '0') {
    accountUsername.value = '';
    accountPassword.value = '';
    accountFormRef.value?.resetFields();
  } else {
    phoneNumber.value = '';
    verificationCode.value = '';
    phoneFormRef.value?.resetFields();
  }
};

// 账号登录处理
const handleAccountLogin = async (): Promise<void> => {
  if (accountFormRef.value) {
    try {
      // 进行表单验证
      const values = await accountFormRef.value.validateFields(['username', 'password']);
      console.log('账号登录成功', values);
      // 这里可以添加实际的登录逻辑
      isLoginError.value = false;
    } catch (errorInfo) {
      console.error('账号登录失败，表单验证不通过', errorInfo);
      message.error('请填写完整的账号和密码');
    }
  }
};

// 手机号登录处理
const handlePhoneLogin = async (): Promise<void> => {
  if (phoneFormRef.value) {
    try {
      const values = await phoneFormRef.value.validateFields(['phone', 'code']);
      console.log('手机号登录成功', values);
      // 这里可以添加实际的登录逻辑
    } catch (errorInfo) {
      console.error('手机号登录失败，表单验证不通过', errorInfo);
      message.error('请填写完整的手机号和验证码');
    }
  }
};

// 获取验证码
const getCaptcha = (e: Event): void => {
  // 阻止默认事件
  e.preventDefault();
  // 验证手机号是否填写
  const phoneRegex = /^1[3-9]\d{9}$/;
  if (!phoneRegex.test(phoneNumber.value)) {
    message.error('请输入正确的手机号');
    return;
  }
  console.log('发送验证码到：', phoneNumber.value);
  // 这里可以添加实际的发送验证码逻辑
  // 开始倒计时
  startCountdown();
};

// 处理第三方登录
const handleThirdPartyLogin = (platform: string) => {
  console.log(`开始使用 ${platform} 登录`);
  // 这里可以添加实际的第三方登录逻辑，例如跳转到授权页面等
};
</script>

<style lang="less" scoped>
body {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin: 0;
  padding: 16px;
  font-size: 16px;
}

.login-container {
  width: 100%;
  max-width: 400px;
  min-width: 400px;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  background-color: rgba(255, 255, 255, 0.9);
  box-sizing: border-box;
  height: auto; /* 调整为 auto 以适应新增内容 */
  overflow-y: auto;
  transition: all 0.3s ease;
  /* 确保登录容器水平和垂直居中 */
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.login-container h1 {
  text-align: center;
  margin-bottom: 20px;
  font-size: 24px;
  color: #333;
}

.centered-tabs {
  .ant-tabs-nav {
    margin: 0 auto;
    display: flex;
    justify-content: center;
  }
}

.ant-tabs-nav-list {
  width: 100%;
  height: 100%;
}

.ant-form-item {
  margin-bottom: 16px;
}

.ant-input,
.ant-input-password {
  height: 44px;
  font-size: 16px;
  border-radius: 4px;
  border: 1px solid #ccc;
  transition: border-color 0.3s ease;

  &:focus {
    border-color: #1890ff;
    outline: none;
  }
}

.ant-btn {
  height: 44px;
  font-size: 16px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.ant-row {
  display: flex;
  flex-wrap: nowrap;
}

.ant-col {
  display: flex;
}

.ant-col:nth-child(2) .ant-btn {
  width: 100%;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-container {
    max-width: 100%;
    min-width: auto;
    padding: 16px;
    height: auto;
    position: static;
    transform: none;
  }

  .login-container h1 {
    font-size: 20px;
  }

  .ant-input,
  .ant-input-password,
  .ant-btn {
    height: 40px;
    font-size: 14px;
  }

  .ant-form-item {
    margin-bottom: 12px;
  }
}

/* 增强按钮交互反馈 */
.ant-btn {
  transition: background-color 0.2s ease;
}

.ant-btn-primary {
  background-color: #1890ff;
  border-color: #1890ff;

  &:hover {
    background-color: #40a9ff;
    border-color: #40a9ff;
  }
}

.ant-btn:hover {
  cursor: pointer;
}

/* 过渡动画样式 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 获取验证码按钮样式 */
.get-code-btn {
  padding: 0 8px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 版权声明样式 */
.copyright {
  color: rgba(0, 0, 0, 0.5);
  font-size: 14px;
  margin-top: auto;
  text-align: center;
  width: 100%;
  position: absolute;
  bottom: 16px;
}

/* 添加选项卡切换动画 */
.ant-tabs-tabpane {
  transition: opacity 0.3s ease;
}

.ant-tabs-tabpane-inactive {
  opacity: 0;
  pointer-events: none;
}

.ant-tabs-tabpane-active {
  opacity: 1;
}

/* 分割线样式 */
.divider {
  display: flex;
  align-items: center;
  margin: 20px 0;

  &::before,
  &::after {
    content: '';
    flex: 1;
    border-bottom: 1px solid #ccc;
  }

  span {
    margin: 0 10px;
    color: #999;
  }
}

/* 第三方登录样式 */
.third-party-login {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-bottom: 10px;
}

.round-button {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0;

  img {
    width: 30px;
    height: 30px;
  }
}
</style>